/**
 * Copyright(C) 2008 Matthias Braunhofer
 * All rights reserved
 *
 * Created on: 30.08.2008
 */

package it.cums.editors;

import it.cums.model.Order;
import it.cums.model.OrderedProduct;
import it.cums.model.OrderedProducts;
import it.cums.util.OrderedProductManager;
import it.cums.wizards.OrderedProductWizard;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

public class ProductsEditTable {
    private Order order;
    private Table table;
    private TableViewer tableViewer;
    private OrderedProducts orderedProducts;
    
    private final static String[] COLUMN_HEADINGS = {"Product", "Price (Euro)", "Quantity", "Total price (Euro)", "Discount (%)", "End price (Euro)"};
    
    public ProductsEditTable(Order order) {
    	this.order = order;
    }
    
    protected Control createContents(Composite parent) {
      	Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout(1, false);
		layout.verticalSpacing = 10;
		composite.setLayout(layout);			
		GridData data = new GridData(GridData.FILL_HORIZONTAL);
		data.horizontalSpan = 3;
		data.heightHint = 160;
		data.grabExcessHorizontalSpace = true;
		composite.setLayoutData(data);
		
		Composite buttonComposite = new Composite(composite, SWT.NONE);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
        buttonComposite.setLayout(gridLayout);
		
		Button addButton = new Button(buttonComposite, SWT.PUSH);
        addButton.setText("Add");
        addButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
            	OrderedProductWizard wizard = new OrderedProductWizard(order);
				WizardDialog dialog = new WizardDialog(table.getShell(), wizard);
				dialog.open();
            }
        });
        
        Button editButton = new Button(buttonComposite, SWT.PUSH);
        editButton.setText("Edit");
        editButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
            	ISelection selection = tableViewer.getSelection();
                if (selection instanceof IStructuredSelection) {
                	Object obj = ((IStructuredSelection)selection).getFirstElement();
                	if (obj instanceof OrderedProduct) {
	                	OrderedProductWizard wizard = new OrderedProductWizard((OrderedProduct)obj);
	    				WizardDialog dialog = new WizardDialog(table.getShell(), wizard);
	    				dialog.open();
                	}
                }
            }
        });
        
        Button removeButton = new Button(buttonComposite, SWT.PUSH);
        removeButton.setText("Remove");
        removeButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                ISelection selection = tableViewer.getSelection();
                if (selection instanceof IStructuredSelection) {
                	Object obj = ((IStructuredSelection)selection).getFirstElement();
                	if (obj instanceof OrderedProduct) {
                		orderedProducts.removeOrderedProduct((OrderedProduct)obj);
                	}
                }
            }
        });
		
		table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION);
		table.setLinesVisible(true);
        table.setHeaderVisible(true);
        data = new GridData(GridData.FILL_BOTH);
        table.setLayoutData(data);
         
        TableLayout tableLayout = new TableLayout();
        table.setLayout(tableLayout);
        
        tableLayout.addColumnData(new ColumnWeightData(15, 118, true));
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText(COLUMN_HEADINGS[0]);
        column.setAlignment(SWT.LEFT);
        
        tableLayout.addColumnData(new ColumnWeightData(15, 118, true));
        column = new TableColumn(table, SWT.NONE);
        column.setText(COLUMN_HEADINGS[1]);
        column.setAlignment(SWT.LEFT);
        
        tableLayout.addColumnData(new ColumnWeightData(15, 118, true));
        column = new TableColumn(table, SWT.NONE);
        column.setText(COLUMN_HEADINGS[2]);
        column.setAlignment(SWT.LEFT);
        
        tableLayout.addColumnData(new ColumnWeightData(15, 118, true));
        column = new TableColumn(table, SWT.NONE);
        column.setText(COLUMN_HEADINGS[3]);
        column.setAlignment(SWT.LEFT);
        
        tableLayout.addColumnData(new ColumnWeightData(15, 118, true));
        column = new TableColumn(table, SWT.NONE);
        column.setText(COLUMN_HEADINGS[4]);
        column.setAlignment(SWT.LEFT);
        
        tableLayout.addColumnData(new ColumnWeightData(15, 118, true));
        column = new TableColumn(table, SWT.NONE);
        column.setText(COLUMN_HEADINGS[5]);
        column.setAlignment(SWT.LEFT);
 		
		return composite;
    }
    
    public void initialize(Order order) {
    	this.order = order;
    	List<OrderedProduct> orderedProductsList = OrderedProductManager.getInstance().listOrderedProducts(order);
    	OrderedProducts products = new OrderedProducts();
    	for (OrderedProduct orderedProduct : orderedProductsList) {
			products.addOrderedProduct(orderedProduct);
		}
    	this.orderedProducts = products;
    	order.setOrderedProducts(orderedProducts);
    	tableViewer = new TableViewer(table);
        tableViewer.setColumnProperties(COLUMN_HEADINGS);
        tableViewer.setContentProvider(new TableContentProvider());
        tableViewer.setLabelProvider(new TableLabelProvider());
        tableViewer.setInput(orderedProducts);
    }
       
	public class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
	    public Image getColumnImage(Object element, int columnIndex) {
	        return null;
	    }
	    
	    @Override
	    public boolean isLabelProperty(Object element, String property) {
	    	// TODO Auto-generated method stub
	    	if (property.equals("Product")) {
	    		return true;
	    	}
	    	return super.isLabelProperty(element, property);
	    }

        public String getColumnText(Object element, int columnIndex) {
        	OrderedProduct product = (OrderedProduct) element;
            
            switch (columnIndex) {
            case 0:
                return product.getProduct();
            case 1:
                return String.valueOf(product.getPrice());
            case 2:
                return String.valueOf(product.getQuantity());
            case 3:
                return String.valueOf(product.getTotalPrice());
            case 4:
                return String.valueOf(product.getDiscount());
            case 5:
                return String.valueOf(product.getEndPrice());
            }
            return null;
        }

	}

	public class TableContentProvider implements IStructuredContentProvider, PropertyChangeListener {
        
		public TableContentProvider() {
			orderedProducts = order.getOrderedProducts();
			orderedProducts.addChangeListener(this);
		}
		
		public Object[] getElements(Object parent) {
			return orderedProducts.getOrderedProducts().toArray();
        }
        
        public void dispose() {
        	orderedProducts.removeChangeListener(this);
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }

		@Override
		public void propertyChange(PropertyChangeEvent arg0) {
			tableViewer.refresh();
		}
	}
}
